﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Model;
using MySql.Data.MySqlClient;

namespace DAL
{
    public class SOP_ProductKeyLogsDAL
    {
        #region 添加日志
        /// <summary>
        /// 申请帐号
        /// </summary>
        /// <param name="model"></param>
        /// <param name="companyId"></param>
        /// <returns></returns>
        public int Register(SOP_ProductKeyLogs model,out int companyId)
        {
            companyId=0;
            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetSOPMySqlConnection(true))
            {
                try
                {
                    MySqlCommand cmd = new MySqlCommand("P_RegisterProductKeyLogs_arcyun", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@UserId_Para", MySqlDbType.Int32).Value = model.UserId;
                    cmd.Parameters.Add("@CompanyId_Para", MySqlDbType.Int32).Value = model.CompanyId;
                    cmd.Parameters.Add("@Step_Para", MySqlDbType.Int32).Value = model.StepObj;
                    cmd.Parameters.Add("@CompanyName_Para", MySqlDbType.VarChar,200).Value = model.CompanyName;
                    cmd.Parameters.Add("@Business_Para", MySqlDbType.VarChar,500).Value = model.Business;
                    cmd.Parameters.Add("@ContactPerson_Para", MySqlDbType.VarChar, 30).Value = model.ContactPerson;
                    cmd.Parameters.Add("@ContactMobile_Para", MySqlDbType.VarChar, 30).Value = model.ContactMobile;
                    cmd.Parameters.Add("@ContactQQ_Para", MySqlDbType.VarChar, 30).Value = model.ContactQQ;
                    cmd.Parameters.Add("@BusinessLicence_Para", MySqlDbType.VarChar, 200).Value = model.BusinessLicence;
                    cmd.Parameters.Add("@CardPositive_Para", MySqlDbType.VarChar, 200).Value = model.CardPositive;
                    cmd.Parameters.Add("@CardNegative_Para", MySqlDbType.VarChar, 200).Value = model.CardNegative;
                    cmd.Parameters.Add("@SubTotal_Para", MySqlDbType.Decimal).Value = model.SubTotal;
                    cmd.Parameters.Add("@RealTotal_Para", MySqlDbType.Decimal).Value = model.RealTotal;
                    cmd.Parameters.Add("@AppConfig_Para", MySqlDbType.VarChar,100).Value = model.AppConfig;
                    cmd.Parameters.Add("@ApplyType_Para", MySqlDbType.Int32).Value = model.ApplyType;
                    cmd.Parameters.Add("@Status_Para", MySqlDbType.Int32).Value = model.Status;
                    cmd.Parameters.Add("@AddTime_Para", MySqlDbType.DateTime).Value = model.AddTime;
                    cmd.Parameters.Add("@IsSuccess_Para", MySqlDbType.Int32).Value = 0;
                    cmd.Parameters.Add("@OutCompanyId_Para", MySqlDbType.Int32).Value = 0;
                    cmd.Parameters["@IsSuccess_Para"].Direction = ParameterDirection.Output;
                    cmd.Parameters["@OutCompanyId_Para"].Direction = ParameterDirection.Output;
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    cmd.ExecuteNonQuery();
                    Object IsSuccessObj = cmd.Parameters["@IsSuccess_Para"].Value;
                    Object CompanyIdObj = cmd.Parameters["@OutCompanyId_Para"].Value;
                    int isSuccess = IsSuccessObj == null || IsSuccessObj.ToString() == string.Empty ? -5 : (int)IsSuccessObj;
                    companyId = CompanyIdObj == null || CompanyIdObj.ToString() == string.Empty ? -5 : (int)CompanyIdObj;
                    return isSuccess;

                }
                catch (Exception ex)
                {
                    ActCommon.Log.WriteLog("SOP_ProductKeyLogsDAL_Register(date:'" + System.DateTime.Now + "'),error:" + ex.Message, "AddCompany");
                    return -1000;
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        /// <summary>
        /// 获取SOP_ProductKeyLogsDAL
        /// </summary>
        /// <param name="BossID"></param>
        /// <returns></returns>
        public SOP_ProductKeyLogs GetAllProductKeyLogsByBossID(int CompanyId,int UserId,string strWhere)
        {
            SOP_ProductKeyLogs model = null;
            using (MySqlConnection conn = SqlHelper.Settings.GetSOPMySqlConnection(false))
            {
                try
                {
                    StringBuilder strSql = new StringBuilder();
                    strSql.Append("SELECT CompanyId,UserId,CompanyName,Business,ContactPerson,ContactMobile,ContactQQ,BusinessLicence,CardPositive,CardNegative,SubTotal,RealTotal,ApplyType,Status,AddTime,LastUpdateTime FROM SOP_ProductKeyLogs ");
                    strSql.Append(" where CompanyId=@CompanyId_Para and UserId=@UserId_Para ");
                    if (strWhere!="")
                     strSql.Append(strWhere);
                    MySqlCommand cmd = new MySqlCommand(strSql.ToString(), conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@CompanyId_Para", MySqlDbType.Int32).Value = CompanyId;
                    cmd.Parameters.Add("@UserId_Para", MySqlDbType.Int32).Value = UserId;
                   
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    MySqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (sdr != null)
                    {
                        while (sdr.Read())
                        {
                            model = new SOP_ProductKeyLogs();
                            if (sdr["CompanyId"] != DBNull.Value)
                                model.CompanyId = Convert.ToInt32(sdr["CompanyId"]);
                            if (sdr["UserId"] != DBNull.Value)
                                model.UserId = Convert.ToInt32(sdr["UserId"]);
                            if (sdr["CompanyName"] != DBNull.Value)
                                model.CompanyName = sdr["CompanyName"].ToString();
                            if (sdr["Business"] != DBNull.Value)
                                model.Business = sdr["Business"].ToString();
                            if (sdr["ContactPerson"] != DBNull.Value)
                                model.ContactPerson = sdr["ContactPerson"].ToString();
                            if (sdr["ContactMobile"] != DBNull.Value)
                                model.ContactMobile = sdr["ContactMobile"].ToString();
                            if (sdr["ContactQQ"] != DBNull.Value)
                                model.ContactQQ = sdr["ContactQQ"].ToString();
                            if (sdr["BusinessLicence"] != DBNull.Value)
                                model.BusinessLicence = sdr["BusinessLicence"].ToString();
                            if (sdr["CardPositive"] != DBNull.Value)
                                model.CardPositive = sdr["CardPositive"].ToString();
                            if (sdr["CardNegative"] != DBNull.Value)
                                model.CardNegative = sdr["CardNegative"].ToString();
                            if (sdr["SubTotal"] != DBNull.Value)
                                model.SubTotal = Decimal.Parse(sdr["SubTotal"].ToString());
                            if (sdr["RealTotal"] != DBNull.Value)
                                model.RealTotal = Decimal.Parse(sdr["RealTotal"].ToString());
                            if (sdr["ApplyType"] != DBNull.Value)
                                model.ApplyType = Int32.Parse(sdr["ApplyType"].ToString());
                            if (sdr["Status"] != DBNull.Value)
                                model.Status = Int32.Parse(sdr["Status"].ToString());
                            if (sdr["AddTime"] != DBNull.Value)
                                model.AddTime = DateTime.Parse(sdr["AddTime"].ToString());
                            if (sdr["LastUpdateTime"] != DBNull.Value)
                                model.LastUpdateTime = DateTime.Parse(sdr["LastUpdateTime"].ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    ActCommon.Log.WriteLog("SOP_ProductKeyLogsDAL_GetAllProductKeyLogsByBossID(date:'" + System.DateTime.Now + "'),error:" + ex.Message, "AddCompany");
                }
                finally
                {
                    conn.Close();
                }
            }

            return model;
        }


        /// <summary>
        /// 获取注册用户下帐号
        /// </summary>
        /// <param name="BossID"></param>
        /// <returns></returns>
        public IList<SOP_ProductKeyLogs> GetAllProductKeyLogsByBossID(int UserId, string strWhere)
        {
            IList<SOP_ProductKeyLogs> _getlist = new List<SOP_ProductKeyLogs>();
            using (MySqlConnection conn = SqlHelper.Settings.GetSOPMySqlConnection(false))
            {
                try
                {
                    StringBuilder strSql = new StringBuilder();
                    strSql.Append("SELECT CompanyId,UserId,CompanyName,Business,ContactPerson,ContactMobile,ContactQQ,BusinessLicence,CardPositive,CardNegative,SubTotal,RealTotal,ApplyType,Status,AddTime,LastUpdateTime FROM SOP_ProductKeyLogs ");
                    strSql.Append(" where UserId=@UserId_Para ");
                    if (strWhere != "")
                        strSql.Append(strWhere);
                    MySqlCommand cmd = new MySqlCommand(strSql.ToString(), conn);

                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@UserId_Para", MySqlDbType.Int32).Value = UserId;
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    MySqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (sdr != null)
                    {
                        while (sdr.Read())
                        {
                            SOP_ProductKeyLogs model = new SOP_ProductKeyLogs();
                            if (sdr["CompanyId"] != DBNull.Value)
                                model.CompanyId = Convert.ToInt32(sdr["CompanyId"]);
                            if (sdr["UserId"] != DBNull.Value)
                                model.UserId = Convert.ToInt32(sdr["UserId"]);
                            if (sdr["CompanyName"] != DBNull.Value)
                                model.CompanyName = sdr["CompanyName"].ToString();
                            if (sdr["Business"] != DBNull.Value)
                                model.Business = sdr["Business"].ToString();
                            if (sdr["ContactPerson"] != DBNull.Value)
                                model.ContactPerson = sdr["ContactPerson"].ToString();
                            if (sdr["ContactMobile"] != DBNull.Value)
                                model.ContactMobile = sdr["ContactMobile"].ToString();
                            if (sdr["ContactQQ"] != DBNull.Value)
                                model.ContactQQ = sdr["ContactQQ"].ToString();
                            if (sdr["BusinessLicence"] != DBNull.Value)
                                model.BusinessLicence = sdr["BusinessLicence"].ToString();
                            if (sdr["CardPositive"] != DBNull.Value)
                                model.CardPositive = sdr["CardPositive"].ToString();
                            if (sdr["CardNegative"] != DBNull.Value)
                                model.CardNegative = sdr["CardNegative"].ToString();
                            if (sdr["SubTotal"] != DBNull.Value)
                                model.SubTotal = Decimal.Parse(sdr["SubTotal"].ToString());
                            if (sdr["RealTotal"] != DBNull.Value)
                                model.RealTotal = Decimal.Parse(sdr["RealTotal"].ToString());
                            if (sdr["ApplyType"] != DBNull.Value)
                                model.ApplyType = Int32.Parse(sdr["ApplyType"].ToString());
                            if (sdr["Status"] != DBNull.Value)
                                model.Status = Int32.Parse(sdr["Status"].ToString());
                            if (sdr["AddTime"] != DBNull.Value)
                                model.AddTime = DateTime.Parse(sdr["AddTime"].ToString());
                            if (sdr["LastUpdateTime"] != DBNull.Value)
                                model.LastUpdateTime = DateTime.Parse(sdr["LastUpdateTime"].ToString());

                            _getlist.Add(model);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ActCommon.Log.WriteLog("SOP_ProductKeyLogsDAL_GetAllProductKeyLogsByBossID(date:'" + System.DateTime.Now + "'),error:" + ex.Message, "AddCompany");
                    return null;
                }
                finally
                {
                    conn.Close();
                }
            }

            return _getlist;
        }


        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="CompanyId"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public int UpdateProductKeyLogs(int CompanyId,int UserId)
        {

            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetSOPMySqlConnection(true))
            {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("update SOP_ProductKeyLogs set Status=1,LastUpdateTime='"+System.DateTime.Now+"' where CompanyId='"+CompanyId+"' and UserId='"+UserId+"';");
                    string strsql = sb.ToString();
                    MySqlCommand cmd = new MySqlCommand(strsql, conn);
                    cmd.CommandType = CommandType.Text;
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    return cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    ActCommon.Log.WriteLog("SOP_ProductKeyLogsDAL_UpdateProductKeyLogs(date:'" + System.DateTime.Now + "'),error:" + ex.Message, "AddCompany");
#if DEBUG
                    throw ex;
#else
                   return -10000;
#endif
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        #endregion

        #region 获取vipuser和username
        /// <summary>
        /// 取得新的账号ID
        /// </summary>
        /// <param name="brandType">取得商户类型 5多品牌 10 单品牌</param>
        /// <param name="recordSize">取得店铺账号的个数</param>
        /// <returns>账号信息</returns>
        public int GetNewUserId(int brandType, int recordSize, out string VipUserID, out string UserName)
        {
            VipUserID = "";
            UserName = "";
            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetSOPMySqlConnection(true))
            {
                try
                {
                    MySqlCommand cmd = new MySqlCommand("P_GetNewUserId", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@BrandType_Para", MySqlDbType.Int32).Value = brandType;
                    cmd.Parameters.Add("@RecordSize_Para", MySqlDbType.Int32).Value = recordSize;
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    using (MySqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        while (sdr.Read())
                        {
                            if (sdr["DataInfo"] != DBNull.Value && sdr["DataType"] != DBNull.Value)
                            {
                                string val = sdr["DataType"].ToString();
                                if (val == "userid")
                                {
                                    VipUserID = sdr["DataInfo"].ToString();
                                }
                                else if (val == "username10")
                                {
                                    UserName = sdr["DataInfo"].ToString();
                                }
                            }


                        }
                    }
                    if (VipUserID == "" || UserName == "")
                    {
                        return -5;
                    }
                    else
                    {
                        return 5;
                    }
                }
                catch (Exception ex)
                {
                    ActCommon.Log.WriteLog("SOP_ProductKeyLogsDAL_GetNewUserId(date:'" + System.DateTime.Now + "'),error:" + ex.Message, "AddCompany");
#if DEBUG
                    throw ex;
#else
                    return -1000;
#endif
                }
                finally
                {
                    conn.Close();
                }
            }
        }
        #endregion
        #region app
        //获取可以开通的app数据
        public IList<ArcSoftCloudApp> GetUseArcSoftCloudApp()
        {
            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetSOPMySqlConnection(true))
            {
                try
                {
                    MySqlCommand cmd = new MySqlCommand("P_GetUseArcSoftCloudApp", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    IList<ArcSoftCloudApp> List = new List<ArcSoftCloudApp>();
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    using (MySqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        while (sdr.Read())
                        {
                            ArcSoftCloudApp Ent = new ArcSoftCloudApp();
                            if (sdr["CloudAppID"] != DBNull.Value)
                                Ent.CloudAppID = (Int32)sdr["CloudAppID"];
                            if (sdr["BusinessType"] != DBNull.Value)
                                Ent.BusinessType = (Int32)sdr["BusinessType"];
                            if (sdr["AppName"] != DBNull.Value)
                                Ent.AppName = (String)sdr["AppName"];
                            if (sdr["AppType"] != DBNull.Value)
                                Ent.AppType = (Int32)sdr["AppType"];
                            if (sdr["Appkey"] != DBNull.Value)
                                Ent.Appkey = (String)sdr["Appkey"];
                            if (sdr["AppVersion"] != DBNull.Value)
                                Ent.AppVersion = (String)sdr["AppVersion"];
                            if (sdr["VersionType"] != DBNull.Value)
                                Ent.VersionType = (Int32)sdr["VersionType"];
                            if (sdr["AppPermission"] != DBNull.Value)
                                Ent.AppPermission = (String)sdr["AppPermission"];
                            if (sdr["AppDesc"] != DBNull.Value)
                                Ent.AppDesc = (String)sdr["AppDesc"];
                            if (sdr["AppSecret"] != DBNull.Value)
                                Ent.AppSecret = (String)sdr["AppSecret"];
                            if (sdr["AppPicUrl"] != DBNull.Value)
                                Ent.AppPicUrl = (String)sdr["AppPicUrl"];
                            if (sdr["StarNum"] != DBNull.Value)
                                Ent.StarNum = (Int32)sdr["StarNum"];
                            if (sdr["IsNeedDownload"] != DBNull.Value)
                                Ent.IsNeedDownload = (Int32)sdr["IsNeedDownload"];
                            if (sdr["DownloadAddress"] != DBNull.Value)
                                Ent.DownloadAddress = (String)sdr["DownloadAddress"];
                            if (sdr["OperatorID"] != DBNull.Value)
                                Ent.OperatorID = (String)sdr["OperatorID"];
                            if (sdr["OperatorName"] != DBNull.Value)
                                Ent.OperatorName = (String)sdr["OperatorName"];
                            if (sdr["Remark"] != DBNull.Value)
                                Ent.Remark = (String)sdr["Remark"];
                            if (sdr["Status"] != DBNull.Value)
                                Ent.Status = (Int32)sdr["Status"];
                            if (sdr["AddTime"] != DBNull.Value)
                                Ent.AddTime = (DateTime)sdr["AddTime"];
                            List.Add(Ent);
                        }
                    }
                    return List;
                }
                catch (Exception ex)
                {
                    ActCommon.Log.WriteLog("SOP_ProductKeyLogsDAL_GetUseArcSoftCloudApp(date:'" + System.DateTime.Now + "'),error:" + ex.Message, "AddCompany");
#if DEBUG
                    throw ex;
#else
                    return null;
#endif
                }
                finally
                {
                    conn.Close();
                }
            }
        }
        public int AddApplyByList(IList<AppApply> List, string VipUserID)
        {
            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetSOPMySqlConnection(true))
            {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    if (VipUserID != "")
                    {
                        sb.AppendFormat("DELETE  from SOP_AppApply where  VipUserID=" + VipUserID + "; ");
                    }
                    sb.AppendFormat("insert into SOP_AppApply(VipUserID,AppID,AppName,ApplyAmount,Status,AddUser,AddTime) values ");
                    foreach (AppApply rl in List)
                    {
                        sb.AppendFormat("('{0}','{1}','{2}','{3}','{4}','{5}','{6}'),", rl.VipUserID, rl.AppID, rl.AppName, rl.ApplyAmount, rl.Status, rl.AddUser, rl.AddTime);
                    }
                    string strsql = sb.ToString();
                    if (strsql.Length > 0 && strsql.EndsWith(","))
                    {
                        strsql = strsql.Substring(0, strsql.Length - 1);
                    }
                    MySqlCommand cmd = new MySqlCommand(strsql, conn);
                    cmd.CommandType = CommandType.Text;
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    return cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    ActCommon.Log.WriteLog("SOP_ProductKeyLogsDAL_AddApplyByList(date:'" + System.DateTime.Now + "'),error:" + ex.Message, "AddCompany");
#if DEBUG
                    throw ex;
#else
                   return -10000;
#endif
                }
                finally
                {
                    conn.Close();
                }
            }
        }
        #endregion
        #region 权限模块
        //获取某个类型对应模块
        public int SetBrandVersionPermissionsByBossVersionType(string VipUserID, int VersionType)
        {


            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetBrandMySqlConnection(true))
            {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    if (VipUserID != "")
                    {
                        sb.AppendFormat("DELETE  from CR_BrandPermissions where  OperatorID=" + VipUserID + "; ");
                        sb.AppendFormat("INSERT INTO CR_BrandPermissions (PermissionID,PermissionName,Controller,Action,ActionType,Remark,Status,OperatorID,OperatorName,AddTime,Pic,Sort,IsShow) select  a.PermissionID,a.PermissionName,a.Controller,a.Action,a.ActionType,a.Remark,a.Status,'" + VipUserID + "','',a.AddTime,a.Pic,a.Sort,a.IsShow from   CR_ArcSoftPermissions a left join CR_BrandVersionPermissions b  on  b.BossVersionType=" + VersionType + " and a.PermissionID=b.PermissionID where a.Status=5 and left(a.PermissionID,2) not in(34); ");
                    }
                    string strsql = sb.ToString();
                    MySqlCommand cmd = new MySqlCommand(strsql, conn);
                    cmd.CommandType = CommandType.Text;
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    return cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    ActCommon.Log.WriteLog("SOP_ProductKeyLogsDAL_SetBrandVersionPermissionsByBossVersionType(date:'" + System.DateTime.Now + "'),error:" + ex.Message, "AddCompany");
#if DEBUG
                    throw ex;
#else
                   return -10000;
#endif
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        #endregion
    }
}
